package com.cc.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cc.entity.EmployeeProfiles;
import com.cc.entity.Page;
import com.cc.service.UserService;
import com.cc.service.impl.UserServiceImpl;
import com.cc.util.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/oa.action")
public class OaServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String option = req.getParameter("option")==null?"":req.getParameter("option");
        switch (option){
            case "emp":
                getEmp(req,resp);
                break;
            case "dashboard":
                getDashboard(req,resp);
                break;
            case "list":
                getList(req,resp);
                break;
            case "add":
                empAdd(req,resp);
                break;
            case "edit":
                empEdit(req,resp);
                break;
            case "update":
                empUpdate(req,resp);
                break;
            case "delete":
                empDelete(req,resp);
                break;
            default:
                break;
        }
    }

    /**
     * 根据用户ID获取员工信息
     *
     * @param req 用于获取请求参数的HttpServletRequest对象
     * @param resp 用于向客户端发送响应的HttpServletResponse对象
     */
    private void getEmp(HttpServletRequest req, HttpServletResponse resp) {
        // 从请求参数中获取用户ID
        String userId = req.getParameter("userId");
        // 设置响应内容类型为JSON格式，编码为UTF-8
        resp.setContentType("application/json;charset=UTF-8");
        // 检查用户ID是否不为空
        if(userId!=null){
            // 通过用户服务根据用户ID获取员工信息
            EmployeeProfiles employeeProfiles = userService.getEmployeeById(Integer.parseInt(userId));
            // 将员工信息转换为JSON字符串
            String json = JSON.toJSONString(employeeProfiles);
            // 尝试将JSON字符串写入响应中
            try {
                resp.getWriter().write(json);
            } catch (IOException e) {
                // 如果发生IO异常，则打印异常信息
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取用户仪表盘信息
     * 根据请求中的userId参数，获取对应员工的档案信息，并以JSON格式返回
     * 如果userId为null，则不执行任何操作
     *
     * @param req  HttpServletRequest对象，用于获取请求参数
     * @param resp HttpServletResponse对象，用于设置响应内容类型和写入响应体
     */
    private void getDashboard(HttpServletRequest req, HttpServletResponse resp) {
        // 从请求参数中获取userId
        String userId = req.getParameter("userId");
        // 设置响应内容类型为JSON，字符编码为UTF-8
        resp.setContentType("application/json;charset=UTF-8");
        // 如果userId不为null，则根据userId获取员工档案信息
        if(userId!=null){
            // 通过userService根据userId获取员工档案对象
            EmployeeProfiles employeeProfiles = userService.getEmployeeById(Integer.parseInt(userId));
            // 将员工档案对象转换为JSON字符串
            String json = JSON.toJSONString(employeeProfiles);
            // 尝试将JSON字符串写入响应体中
            try {
                resp.getWriter().write(json);
            } catch (IOException e) {
                // 如果发生IOException，则打印异常堆栈跟踪信息
                e.printStackTrace();
            }
        }
    }

    private void getList(HttpServletRequest req, HttpServletResponse resp) {
        String pageNum = req.getParameter("pageNum");
        Page<EmployeeProfiles> page = new Page<EmployeeProfiles>();
        if (pageNum != null){
            page.setPageNum(Integer.parseInt(pageNum));
        } else {
            page.setPageNum(1);
        }
        page = userService.findEmployeeByPage("",page);
        String json = JSON.toJSONStringWithDateFormat(page,"yyyy-MM-dd", SerializerFeature.WriteNullStringAsEmpty);
        try {
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void empAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 统一设置响应头
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 获取参数
            String userId = req.getParameter("user_id");
            String name = req.getParameter("name");
            String position = req.getParameter("position");
            String department = req.getParameter("department");
            String hireDate = req.getParameter("hire_date");
            String leaveDate = req.getParameter("leave_date");
            String status = req.getParameter("status");

            // 2. 基本参数校验
            if (name == null || name.trim().isEmpty() ||
                    position == null || position.trim().isEmpty() ||
                    department == null || department.trim().isEmpty() ||
                    hireDate == null || hireDate.trim().isEmpty() ||
                    status == null || status.trim().isEmpty()) {

                result.put("success", false);
                result.put("msg", "必填字段不能为空");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 3. 构建实体对象
            EmployeeProfiles emp = new EmployeeProfiles();
            if (userId != null && !userId.trim().isEmpty()) {
                emp.setUserId(Integer.parseInt(userId));
            }
            emp.setName(name.trim());
            emp.setPosition(position.trim());
            emp.setDepartment(department.trim());
            emp.setHireDate(DateUtil.pareDate(hireDate.trim()));
            if (leaveDate != null && !leaveDate.trim().isEmpty()) {
                emp.setLeaveDate(DateUtil.pareDate(leaveDate.trim()));
            }
            emp.setStatus(status.trim());

            // 4. 调用服务层
            boolean success = userService.addEmployee(emp);

            // 5. 返回结果
            result.put("success", success);
            result.put("msg", success ? "员工添加成功！" : "员工添加失败！");

        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("msg", "用户ID必须是数字");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "服务器错误: " + e.getMessage());
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.print(JSON.toJSONString(result));
        }
    }

    private void empEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id != null && !id.isEmpty()) {
            EmployeeProfiles emp = userService.getEmployeeById(Integer.parseInt(id));
            req.setAttribute("emp", emp);
        }
        req.getRequestDispatcher("/pages/edit.jsp").forward(req, resp);
    }

    private void empUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String id = req.getParameter("id");
            String userId = req.getParameter("user_id");
            String name = req.getParameter("name");
            String position = req.getParameter("position");
            String department = req.getParameter("department");
            String hireDate = req.getParameter("hire_date");
            String leaveDate = req.getParameter("leave_date");
            String status = req.getParameter("status");

            // 参数校验
            if (name == null || name.trim().isEmpty() ||
                    position == null || position.trim().isEmpty() ||
                    department == null || department.trim().isEmpty() ||
                    hireDate == null || hireDate.trim().isEmpty() ||
                    status == null || status.trim().isEmpty()) {

                result.put("success", false);
                result.put("msg", "必填字段不能为空");
                out.print(JSON.toJSONString(result));
                return;
            }

            EmployeeProfiles employeeProfiles = new EmployeeProfiles();
            if (id != null && !id.trim().isEmpty()) {
                employeeProfiles.setId(Integer.parseInt(id));
            }
            employeeProfiles.setUserId(Integer.parseInt(userId));
            employeeProfiles.setName(name);
            employeeProfiles.setPosition(position);
            employeeProfiles.setDepartment(department);
            employeeProfiles.setHireDate(DateUtil.pareDate(hireDate));
            if (leaveDate != null && !leaveDate.trim().isEmpty()) {
                employeeProfiles.setLeaveDate(DateUtil.pareDate(leaveDate));
            }
            employeeProfiles.setStatus(status);

            boolean success;
            if (id == null || id.trim().isEmpty()) {
                success = userService.addEmployee(employeeProfiles);
            } else {
                success = userService.updateEmployeeProfiles(employeeProfiles);
            }

            result.put("success", success);
            result.put("msg", success ? "操作成功" : "操作失败");
            out.print(JSON.toJSONString(result));

        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "服务器错误: " + e.getMessage());
            out.print(JSON.toJSONString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
    private void empDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String id = req.getParameter("id");
            if (id == null || id.trim().isEmpty()) {
                result.put("success", false);
                result.put("msg", "ID不能为空");
            } else {
                boolean success = userService.deleteEmployee(Integer.parseInt(id));
                result.put("success", success);
                result.put("msg", success ? "删除成功" : "删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "服务器错误: " + e.getMessage());
        }

        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
